package tech.aistar.controller.noteinfo;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import tech.aistar.config.AlipayConfig;
import tech.aistar.config.GuidelInterceptor;
import tech.aistar.entity.authordis.Notes;
import tech.aistar.entity.authordis.UserTable;
import tech.aistar.service.noteinfo.INoteInfoService;
import tech.aistar.service.noteinfo.INotePayService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by lenovo on 2019/10/10.
 */
@Controller
@RequestMapping("/notePay")

public class NotePayController {

    final static Logger log = LoggerFactory.getLogger(NotePayController.class);

    @Autowired
    public INoteInfoService noteInfoService;

    @Autowired
    public INotePayService notePayService;

    /**
     *前往支付宝第三方网关进行支付
     */
    @GuidelInterceptor
    @RequestMapping(value = "/goAlipay", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String goAlipay(Integer notesId, HttpServletRequest request, HttpServletRequest response, HttpSession session) throws Exception {

        UserTable userTable= (UserTable) session.getAttribute("userId");
        Notes notes = noteInfoService.findNotesById(notesId);

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset,
                AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String t = sdf.format(date);
        String temp = String.valueOf(notesId)+t;

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = temp;
        //付款金额，必填
        String total_amount = "10000";
        //订单名称，必填
        String subject = notes.getTitle();
        session.setAttribute("subject",subject);

//        游记id
        String noteId = String.valueOf(notesId);
        session.setAttribute("noteId",noteId);
        //用户id描述，可空
//        String body = String.valueOf(userTable.getId());
//        //暂时游记id
//        String body = String.valueOf(notesId);
//        session.setAttribute("body",1);

        System.out.println("out_trade_no:"+out_trade_no);
        System.out.println("total_amount:"+total_amount);
        System.out.println("title:"+subject);
//        System.out.println("body:"+body);

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
//                + "\"body\":\""+ body +"\","
                + "\"noteId\":\""+ noteId +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("result :"+result);
        return result;
    }


    /**
     *  支付宝同步通知页面
     */
    @RequestMapping(value = "/alipayReturnNotice")
    public String alipayReturnNotice(HttpServletRequest request, HttpServletRequest response,HttpSession session) throws Exception {

        //游记id
        String noteId = (String) session.getAttribute("noteId");

        log.info("pay successfully ,支付成功, 进入同步通知接口...");
        System.out.println("支付成功后，支付宝返回的所有的数据："+ request);
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            System.out.println("return notice name:"+name);
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println("params:"+params);
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        System.out.println("return notice signVerified:"+signVerified);
//        ModelAndView mv = new ModelAndView("noteinfo/alipaySuccess");
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            //用户id
            UserTable userTable = (UserTable) session.getAttribute("userId");
            Integer body = userTable.getId();

            //游记名
            String subject = (String) session.getAttribute("subject");
            //获取当前系 统时间
            Date date = new Date();
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = df.format(date);

            System.out.println("return out_trade_no:"+out_trade_no);
            System.out.println("return trade_no:"+trade_no);
            System.out.println("return total_amount:"+total_amount);
            //	System.out.println("return productName:"+ product.getName());

            notePayService.updateOrderStatus(body,out_trade_no,trade_no,Double.valueOf(total_amount),time,Integer.valueOf(noteId),subject);

            log.info("********************** 支付成功(支付宝同步通知) **********************");
            log.info("* 订单号: {}", out_trade_no);
            log.info("* 支付宝交易号: {}", trade_no);
            log.info("* 实付金额: {}", total_amount);
            log.info("* 购买产品: {}",subject );
            log.info("***************************************************************");


//            mv.addObject("out_trade_no", out_trade_no);
//            mv.addObject("trade_no", trade_no);
//            mv.addObject("total_amount", total_amount);
//            mv.addObject("productName",subject);

        }else {
            log.info("支付, 验签失败...");
        }

        return "redirect:/noteInfoDis/noteDis?id="+noteId;
    }

    /**
     *
     * @Description: 支付宝异步 通知页面
     *
     */
    @RequestMapping(value = "/alipayNotifyNotice")
    @ResponseBody
    public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response,HttpSession session) throws Exception {

        log.info("支付成功, 进入异步通知接口...");

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

		/* 实际验证过程建议商户务必添加以下校验：
		1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
		2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
		3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
		4、验证app_id是否为该商户本身。
		*/
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            //用户id
            UserTable userTable = (UserTable) session.getAttribute("userId");
            Integer body = userTable.getId();

            //游记id
            String noteId = (String) session.getAttribute("noteId");
            //游记名
            String subject = (String) session.getAttribute("subject");
            //获取当前系统时间
            Date date = new Date();
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = df.format(date);

            System.out.println("return out_trade_no:"+out_trade_no);
            System.out.println("return trade_no:"+trade_no);
            System.out.println("return total_amount:"+total_amount);
            //	System.out.println("return productName:"+ product.getName());

            notePayService.updateOrderStatus(Integer.valueOf(body),out_trade_no,trade_no,Double.valueOf(total_amount),time,Integer.valueOf(noteId),subject);

            log.info("********************** 支付成功(支付宝同步通知) **********************");
            log.info("* 订单号: {}", out_trade_no);
            log.info("* 支付宝交易号: {}", trade_no);
            log.info("* 实付金额: {}", total_amount);
//            log.info("* 购买产品: {}",title );
            log.info("***************************************************************");

            log.info("支付成功...");

        }else {//验证失败
            log.info("支付, 验签失败...");
        }
        return "success";
    }

}
